package com.tonicgb.shared.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tonicgb.shared.Interceptor.AdminTokenInterceptor;
import com.tonicgb.shared.Interceptor.FrontTokenInterceptor;
import com.tonicgb.shared.handler.ApiResultHandlerMethodReturnValueHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author zhaiyujin
 * @date 2021-09-01 14:50:01
 * @说明  web配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

   private ObjectMapper objectMapper;
   @Value("${adminPath}")
   private String adminPath;
   @Value("${frontPath}")
   private String frontPath;

   @Bean
   AdminTokenInterceptor adminTokenInterceptor(){
       return new AdminTokenInterceptor();
   }
   @Bean
    FrontTokenInterceptor frontTokenInterceptor(){
       return new FrontTokenInterceptor();
   }

   public WebMvcConfig(ObjectMapper objectMapper){
       this.objectMapper=objectMapper;

   }
    //自定义返回值
    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        handlers.add(new ApiResultHandlerMethodReturnValueHandler(this.objectMapper));
    }

    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    //添加token拦截
    //addPathPatterns添加需要拦截的命名空间；
    //excludePathPatterns添加排除拦截命名空间
    registry.addInterceptor(adminTokenInterceptor()).addPathPatterns(adminPath+"/**");

    registry.addInterceptor(frontTokenInterceptor()).addPathPatterns(frontPath+"/**");


    }
}
